package net.wwang.open.util;

import net.wwang.open.pojo.vo.MenuNodeVO;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author WangWei
 * @date 2020/8/11
 */
public class TreeUtil {
    private static String ROOT_NODE = "-1";
    private static String MENU_NODE = "0";
    public static Map<String, Object> mapArray = new LinkedHashMap<String, Object>();
    public List<MenuNodeVO> menuNodeVOS;
    public List<Object> list = new ArrayList<>();

    public List<Object> treeMenu(List<MenuNodeVO> node) {
        this.menuNodeVOS = node;
        for (MenuNodeVO menuNodeVO : node) {
            Map<String, Object> mapArr = new LinkedHashMap<String, Object>();
            if (menuNodeVO.getParentId().equals(ROOT_NODE)) {
                setTreeMap(mapArr, menuNodeVO);
                list.add(mapArr);
            }
        }
        return list;
    }


    /**
     * 构建孩子节点
     *
     * @param id
     * @return
     */
    public List<?> menuChild(String id) {
        List<Object> lists = new ArrayList<Object>();
        for (MenuNodeVO a : menuNodeVOS) {
            Map<String, Object> childArray = new LinkedHashMap<String, Object>();
            if (a.getParentId().equals(id)) {
                setTreeMap(childArray, a);
                lists.add(childArray);
            }
        }
        return lists;
    }

    /**
     * 构建树节点信息
     *
     * @param mapArr
     * @param menuNodeVO
     */
    private void setTreeMap(Map<String, Object> mapArr, MenuNodeVO menuNodeVO) {
        if (menuNodeVO.getType().equals(MENU_NODE)) {
            mapArr.put("key", menuNodeVO.getId());
            mapArr.put("id", menuNodeVO.getId());
            mapArr.put("name", menuNodeVO.getName());
            mapArr.put("parentId", menuNodeVO.getParentId());
            mapArr.put("type", "目录");
            mapArr.put("children", menuChild(menuNodeVO.getId()));
        } else {
            mapArr.put("key", menuNodeVO.getId());
            mapArr.put("id", menuNodeVO.getId());
            mapArr.put("title", menuNodeVO.getName());
            mapArr.put("parentId", menuNodeVO.getParentId());
            mapArr.put("type", "文档");
        }
    }

}
